import { MaterialIcons } from "@expo/vector-icons";
import React, { useEffect, useRef, useState } from "react";
import {
  Animated,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

interface Tab {
  key: string;
  label: string;
}

interface AnimatedBottomSheetProps {
  /** 是否显示底部弹出层 */
  visible: boolean;
  /** 弹出层标题 */
  title: string;
  /** 标签页数组 */
  tabs?: Tab[];
  /** 标签页切换回调 */
  onTabChange?: (key: string) => void;
  /** 弹出层内容 */
  children: React.ReactNode;
  /** 取消按钮点击回调 */
  onCancel: () => void;
  /** 确认按钮点击回调 */
  onConfirm?: () => void;
  /** 确认按钮文本，默认为"确定" */
  confirmText?: string;
  /** 取消按钮文本，默认为"取消" */
  cancelText?: string;
  /** 是否显示确认按钮，默认为true */
  showConfirmButton?: boolean;
  /** 关闭按钮位置，默认为'left' */
  closeButtonPosition?: "left" | "right";
  /** 圆角大小，默认为0 */
  borderRadius?: number;
}

/**
 * 通用的动画底部弹出层组件
 * 提供统一的动画效果和样式
 */
export default function AnimatedBottomSheet({
  visible,
  title,
  tabs,
  onTabChange,
  children,
  onCancel,
  onConfirm,
  confirmText = "确定",
  cancelText = "取消",
  showConfirmButton = true,
  closeButtonPosition = "left",
  borderRadius = 0,
}: AnimatedBottomSheetProps) {
  const [selectedTab, setSelectedTab] = useState(tabs?.[0]?.key);

  useEffect(() => {
    if (tabs && tabs.length > 0 && !selectedTab) {
      const firstTab = tabs[0];
      setSelectedTab(firstTab.key);
      onTabChange?.(firstTab.key);
    }
  }, [tabs, onTabChange, selectedTab]);
  const insets = useSafeAreaInsets();
  const translateY = useRef(new Animated.Value(300)).current;

  /**
   * 显示底部弹出层动画
   */
  const showBottomSheet = () => {
    Animated.timing(translateY, {
      toValue: 0,
      duration: 300,
      useNativeDriver: true,
    }).start();
  };

  /**
   * 隐藏底部弹出层动画
   */
  const hideBottomSheet = () => {
    Animated.timing(translateY, {
      toValue: 300,
      duration: 300,
      useNativeDriver: true,
    }).start();
  };

  // 监听 visible 状态变化，执行相应动画
  useEffect(() => {
    if (visible) {
      showBottomSheet();
    } else {
      hideBottomSheet();
    }
  });

  if (!visible) {
    return null;
  }

  return (
    <Animated.View
      style={[
        styles.bottomSheet,
        {
          transform: [{ translateY }],
          zIndex: 10000,
          paddingBottom: insets.bottom,
          borderTopLeftRadius: borderRadius,
          borderTopRightRadius: borderRadius,
        },
      ]}
    >
      {/* 头部区域 */}
      <View style={styles.bottomSheetHeader}>
        {closeButtonPosition === "left" ? (
          <>
            <TouchableOpacity
              style={styles.bottomSheetHeaderBtn}
              onPress={onCancel}
            >
              <MaterialIcons name="close" size={20} color="#222" />
            </TouchableOpacity>

            {tabs ? (
              <View style={styles.tabsContainer}>
                {tabs.map((tab) => (
                  <TouchableOpacity
                    key={tab.key}
                    style={[
                      styles.tab,
                      selectedTab === tab.key && styles.selectedTab,
                    ]}
                    onPress={() => {
                      setSelectedTab(tab.key);
                      onTabChange?.(tab.key);
                    }}
                  >
                    <Text
                      style={{
                        fontSize: 14,
                        color: selectedTab === tab.key ? "#222" : "#666"
                      }}
                    >
                      {tab.label}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>
            ) : (
              <Text style={styles.bottomSheetTitle}>{title}</Text>
            )}

            {showConfirmButton && (
              <TouchableOpacity
                style={styles.bottomSheetHeaderBtn}
                onPress={onConfirm}
              >
                <MaterialIcons name="check" size={20} color="#222" />
              </TouchableOpacity>
            )}

            {!showConfirmButton && <View style={styles.bottomSheetHeaderBtn} />}
          </>
        ) : (
          <>
            {showConfirmButton ? (
              <TouchableOpacity
                style={styles.bottomSheetHeaderBtn}
                onPress={onConfirm}
              >
                <MaterialIcons name="check" size={20} color="#222" />
              </TouchableOpacity>
            ) : (
              <View style={styles.bottomSheetHeaderBtn} />
            )}

            <Text style={styles.bottomSheetTitle}>{title}</Text>

            <TouchableOpacity
              style={styles.bottomSheetHeaderBtn}
              onPress={onCancel}
            >
              <MaterialIcons name="close" size={20} color="#222" />
            </TouchableOpacity>
          </>
        )}
      </View>

      {/* 内容区域 */}
      <View style={styles.bottomSheetContent}>{children}</View>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  bottomSheet: {
    backgroundColor: "#fff",
  },
  bottomSheetHeader: {
    paddingVertical: 4,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    borderBottomWidth: 0,
  },
  bottomSheetTitle: {
    fontSize: 14,
    color: "#222",
    flex: 1,
    textAlign: "center",
  },
  bottomSheetHeaderBtn: {
    padding: 8,
    flexDirection: "row",
    alignItems: "center",
    gap: 4,
  },
  cancelText: {
    color: "#666",
  },
  confirmText: {
    color: "#3B82F6",
  },
  bottomSheetContent: {
    flexGrow: 1, // 让内容自然撑开高度
  },
  tabsContainer: {
    flex: 1,
    flexDirection: "row",
    justifyContent: "center",
    gap: 16,
  },
  tab: {
    paddingVertical: 4,
    paddingHorizontal: 8,
  },
  selectedTab: {},
  tabText: {
    fontSize: 14,
    color: "#666",
    fontWeight: "400",
  },
  selectedTabText: {
    color: "#222 !important",
    fontWeight: "400",
  },
});
